package org.example.handle;

import org.apache.commons.codec.binary.Base64;
import org.example.http.Header;
import org.example.http.HttpResponse;
import org.example.http.SimpleHttpRequest;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Optional;

public interface Handle {

    /**
     * 普通文字识别
     *
     * @param image
     * @return
     */
    Object general(BufferedImage image);


    default byte[] bufferedImageToByte(BufferedImage image, String formatName) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, formatName, os);
        } catch (IOException e) {
            // log
        }
        return os.toByteArray();
    }

    /**
     * bufferedImage转换为base64编码字符串
     *
     * @param image
     * @param charset
     * @return
     */
    default String bufferedImageToString(BufferedImage image, Charset charset, String formatName) {
        return new String(Base64.encodeBase64(bufferedImageToByte(image, formatName)), charset);
    }

    default String doGet(String url) {
        HttpResponse response = SimpleHttpRequest.doGet(url);
        return Optional.of(response).filter(v -> !v.success()).orElseThrow(() -> new RuntimeException(response.getMessage())).getBody();
    }

    default String doPost(String url, String body, Header... headers) {
        HttpResponse response = SimpleHttpRequest.doPost(url, body, headers);
        return Optional.of(response).filter(v -> !v.success()).orElseThrow(() -> new RuntimeException(response.getMessage())).getBody();
    }

}
